package com.freemarker.pickdata;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import com.freemarker.vo.TableEntity;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class MyFreeMarker {

	public static String templatePath = "/com/freemarker/template3";
	public static String file_out_path = "D:/freemarker";
	public static String charsetName = "UTF-8";

	private static Configuration configuration = null;

	public static void main(String[] args) throws Exception {

//		DataTransterVO vo = new DataTransterVO("bee_activity_father2016");
//		Map otherMap = new HashMap();
//		otherMap.put("name", "zhangsan");
//		otherMap.put("age", "20");
//		vo.setOtherMap(otherMap);
//
//		new MyFreeMarker().build(vo, "test2.txt", "test2.ftl");
	}

	public static void build(TableEntity tableEntity, String fileName, String templateName) throws Exception {

		configuration = new Configuration();
		configuration.setDefaultEncoding(charsetName);
		configuration.setClassForTemplateLoading(MyFreeMarker.class, templatePath);

		System.out.println("------------文件名称 [ " + fileName + " ] ----------------");

		File newFolder = new File(file_out_path);
		if (!newFolder.exists()) {
			newFolder.mkdirs();
		}

		Template template = null;
		Writer writerOut = null;
		FileOutputStream fos = null;
		try {
			template = configuration.getTemplate(templateName, charsetName);

			fos = new FileOutputStream(new File(file_out_path, fileName));
			writerOut = new BufferedWriter(new OutputStreamWriter(fos, charsetName));

			template.process(tableEntity, writerOut);
			System.out.println("=============[ " + fileName + " ] 生成 OK ! =============");

		} catch (Exception e) {
			System.err.println("=============[ " + fileName + " ] 生成失败=============");
			throw e;
		} finally {
			if (writerOut != null) {
				writerOut.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
	}

}